package com.example.autopera.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author Code_lemon
 * @version 1.0.0
 * @description TODO 微服务架构内部通信
 * @date 2024/10/25 14:24
 * @title RestClientUtils
 */
@Component
public class RestClientUtils {

    @Resource
    private RestTemplate restTemplate;


    /**
     * 发送 GET 请求
     *
     * @param url          请求的 URL
     * @param responseType 响应的类型
     * @param <T>          响应对象的类型
     * @return 响应对象
     */
    public <T> T getForObject(String url, Class<T> responseType) {
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, null, responseType);
        return response.getBody();
    }

    /**
     * 发送 POST 请求
     *
     * @param url          请求的 URL
     * @param requestBody  请求体
     * @param responseType 响应的类型
     * @param <T>          响应对象的类型
     * @return 响应对象
     */
    public <T> T postForObject(String url, Object requestBody, Class<T> responseType) {
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return response.getBody();
    }

}
